package com.intelligent.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.intelligent.dto.SalesOrdersQueryDTO;
import com.intelligent.pojo.SalesOrders;
import com.intelligent.service.SalesOrdersService;
import com.intelligent.utils.Result;
import com.intelligent.vo.SalesOrdersVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@Api(tags = "销售订单管理")
@RequestMapping("/sales/order")
public class SalesOrdersController {

    @Autowired
    private SalesOrdersService salesOrdersService;

    @ApiOperation("分页查询销售订单")
    @PostMapping("/page")
    public Result<Page<SalesOrdersVO>> page(@RequestBody(required = false) SalesOrdersQueryDTO queryDTO) {
        if (queryDTO == null) {
            queryDTO = new SalesOrdersQueryDTO();
        }
        Page<SalesOrdersVO> page = salesOrdersService.pageList(queryDTO);
        return Result.success(page);
    }

    @ApiOperation("新增销售订单")
    @PostMapping
    public Result<Boolean> add(@RequestBody SalesOrders entity,
                               @RequestHeader(value = "X-User-Id", required = false) Long headerUserId,
                               @RequestParam(value = "uId", required = false) Long requestParamUserId) {
        try {
            // 优先级：Body.uId > 请求参数uId > Header:X-User-Id
            if (entity.getUId() == null) {
                if (requestParamUserId != null) {
                    entity.setUId(requestParamUserId);
                } else if (headerUserId != null) {
                    entity.setUId(headerUserId);
                }
            }
            boolean ok = salesOrdersService.addOrder(entity);
            return ok ? Result.success(true) : Result.error("新增失败");
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("新增失败: " + e.getMessage());
        }
    }

    @ApiOperation("根据ID查询")
    @PostMapping("/getById")
    public Result<SalesOrders> getById(@RequestParam("id") Long id) {
        return Result.success(salesOrdersService.getById(id));
    }
}


